package cn.brilliantfuture.commentry.sms;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import cn.brilliantfuture.commentry.util.DateTimeHelper;
import cn.brilliantfuture.commentry.util.HttpUtil;
import cn.brilliantfuture.commentry.util.JDBCDataSource;
import cn.brilliantfuture.commentry.util.MD5;

/**
 * 
 * Title: Communication Entry
 * 
 * Author:  LiTian  
 *
 * Date: 2013-10-18
 * 
 * Description:
 * 
 */
public class SMSDelaySendJob implements Job{
	private static Logger logger = Logger.getLogger(SMSDelaySendJob.class);
	
	/**
	 * 彩信猫信息通道
	 */
	public static final int MMS_CAT_CHANNEL = 1;
	
	/**
	 * 台湾YOYO8信息通道
	 */
	public static final int TAIWAN_YOYO_CHANNEL = 2;
	
	/**
	 * 云通讯信息通道
	 */
	public static final int YUNTONGXUN_CHANNEL = 3;

	public void execute(JobExecutionContext jobec) throws JobExecutionException {
		logger.info("Send delay sms info ...");
		
		List<Object[]> list = new ArrayList<Object[]>();
		
		Connection conn = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_YEAR, -1);
		calendar.set(Calendar.HOUR, 22);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		
		try {
			conn = JDBCDataSource.getConnection();
			conn.setAutoCommit(false);
			pstm = conn.prepareStatement("select sms_delay_info_id, phone, content, channel from sms_delay_info where send = 0 and insert_time >= '" + DateTimeHelper.dateTimeToStr(calendar.getTime(), DateTimeHelper.DEFAULT_DATE_TIME_FORMAT) + "'");
			rs = pstm.executeQuery();
			
			while(rs.next()) {
				Object[] objs = new Object[4];
				objs[0] = rs.getString("phone");
				objs[1] = rs.getObject("content");
				objs[2] = rs.getInt("channel");
				objs[3] = rs.getInt("sms_delay_info_id");
				
				list.add(objs);
			}

			for (Object[] objs : list) {
				String message = (String) objs[1];
				try {
					message = URLEncoder.encode(message, "utf8");
				} catch (UnsupportedEncodingException e) {
					logger.error(e.getMessage());
				}
				
				StringBuffer sb = new StringBuffer();
				
				String returnValue = null;
				
				if (MMS_CAT_CHANNEL == (Integer)objs[2] || TAIWAN_YOYO_CHANNEL == (Integer)objs[2]) {
					if (MMS_CAT_CHANNEL == (Integer)objs[2]){
						sb.append("http://sms.acsm.cn/smsservice-web/SMSMessageServiceChannel?username=acsm&passwd=acsm@197&phones=");
						sb.append(objs[0]);
						sb.append("&content=");
						sb.append(objs[1]);
					} else if (TAIWAN_YOYO_CHANNEL == (Integer)objs[2]){
						Random random = new Random();
						int prodId = random.nextInt(100000000);
						int msgId = random.nextInt(100000000);
						sb.append("http://www.yoyo8.com.tw/SMSBridge.php?");
						sb.append("MemberID=baokulife");
						sb.append("&Password=").append(MD5.getMD5("baokulife:baokulife1:" + prodId + ":" + msgId));
						sb.append("&MobileNo=").append(objs[0]);
						sb.append("&CharSet=U");
						sb.append("&SMSMessage=").append(objs[1]);
						sb.append("&SourceProdID=").append(prodId);
						sb.append("&SourceMsgID=").append(msgId);
					}
					
					returnValue = HttpUtil.getInvoke(sb.toString());
					returnValue = returnValue.replace("\r\n", "");
					logger.info("Return value : " + returnValue);
				} else if (YUNTONGXUN_CHANNEL == (Integer)objs[2]) {
					/*HashMap<String, Object> result = null;
					CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
					restAPI.init("sandboxapp.cloopen.com", "8883");
					restAPI.setAccount("8a48b5514e5298b9014e704f41781c4d", "6657a44a44b54114984a64196d69d434");
					restAPI.setAppId("aaf98f894e52805a014e704f90f919f2");
					
					result = restAPI.sendTemplateSMS(String.valueOf(objs[0]), "1" , String.valueOf(objs[1]).split("\\|"));

					logger.info("SDKTestGetSubAccounts result -> " + result);
			
					if("000000".equals(result.get("statusCode"))){
						@SuppressWarnings("unchecked")
						HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
						Set<String> keySet = data.keySet();
						for(String key:keySet){
							Object object = data.get(key);
							logger.info(key +" = "+object);
						}
						returnValue = "1";
					}else{
						logger.info("错误码 = " + result.get("statusCode") +" 错误信息 = "+result.get("statusMsg"));
						returnValue = "-1";
					}*/
				}
				
				pstm = conn.prepareStatement("insert into send_record(phone, content, sms_channel, status, is_send, insert_time) values (?, ?, ?, ?, ?, now())");
				
				pstm.setString(1, (String) objs[0]);
				pstm.setString(2, (String) objs[1]);
				pstm.setInt(3, (Integer) objs[2]);
				
				if ("1".equals(returnValue)) {
					pstm.setInt(4, 7);
					pstm.setBoolean(5, true);
				}else {
					pstm.setInt(4, 8);
					pstm.setBoolean(5, false);
				}
				
				pstm.executeUpdate();
			}

			for (Object[] objs : list) {
				pstm = conn.prepareStatement("update sms_delay_info set send = 1 where sms_delay_info_id = ?");
				pstm.setInt(1, (Integer) objs[3]);
				pstm.executeUpdate();
			}

			conn.commit();
			conn.setAutoCommit(true);
		
		} catch (Exception e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				logger.error("Rollback fail\n" + e1.getMessage());
			}
			logger.error("Send delay sms info fail\n" + e.getMessage());
		} finally {
			JDBCDataSource.closeResource(conn, pstm, rs);
		}
	}
}
